//
//  ChongZhiView.m
//  AILove
//
//  Created by 甘世清 on 2023/12/30.
//

#import "ChongZhiView.h"
#import "ZSModel.h"
#import <RMStore.h>
#import "JieGuoView.h"
@implementation ChongZhiView

- (void)SQ_UIViewForSelfView{
    self.backgroundColor = UIColor.clearColor;
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleRegular];
    UIVisualEffectView* visualView = [[UIVisualEffectView alloc]initWithEffect:effect];
     visualView.frame =CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT);
      visualView.alpha = 0.92;
     [self addSubview:visualView];
    UIView * bgView = [[UIView alloc]init];
    bgView.backgroundColor = SQHexColor(@"#FFFFFF", 0.24);
    bgView.layer.cornerRadius = 12;
    bgView.layer.masksToBounds = YES;
    [self addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(295);
        make.height.mas_equalTo(418);
        make.centerX.centerY.equalTo(self);
    }];
    
    UILabel * oneLabel= [[UILabel alloc]init];
    oneLabel.text = SQNSLocalString(@"钻石充值");
    oneLabel.textColor = SQColor(@"#FFFFFF");
    oneLabel.font = FONT_BOLD(18);
    [bgView addSubview:oneLabel];
    [oneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgView).offset(20);
        make.centerX.equalTo(bgView);
        make.height.mas_equalTo(18);
    }];
    
    [bgView addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(bgView).insets(UIEdgeInsetsMake(60, 0, 80, 0));
    }];
    
    _guanbi = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(15, 15) midmargin:0];
    _guanbi.image = SQGetImage(@"退出图标");
    [self addSubview:self.guanbi];
    [self.guanbi mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self);
            make.top.equalTo(bgView.mas_bottom);
            make.size.mas_equalTo(45);
    }];
    
    HeaderView * btn = [[HeaderView alloc]init];
    btn.font = FONT_MEDIUM(16);
    btn.text = SQNSLocalString(@"充值钻石");
    btn.layer.cornerRadius = 4;
    btn.headerImage.image = SQGetImage(@"按钮背景");
    [btn.btn addTarget:self action:@selector(SQ_buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bgView.mas_bottom).offset(-20);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(263);
        make.centerX.equalTo(bgView);
    }];
    
    [self SQ_header];
}
-(void)SQ_header{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [HttpTool post:Url9 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        [self.jsonArray removeAllObjects];
        NSArray * array = [ZSModel mj_objectArrayWithKeyValuesArray:httpModel.data];
        [self.jsonArray addObjectsFromArray:array];
        if (array.count > 0) {
            self.seletedModel = array.firstObject;
            [self SQ_RMStore];
        }
        [self.tableView reloadData];
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.data];
    }];
}
-(void)SQ_RMStore{
 
    NSMutableArray * array = [[NSMutableArray alloc]init];
    [self.jsonArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ZSModel * model = (ZSModel*)obj;
        if ([model.appleId isNotEmpty]) {
            [array addObject:model.appleId];
        }
    }];
     [[RMStore defaultStore] requestProducts:[NSSet setWithArray:array] success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
        if([products count] == 0){
            DTLog(@"--------------没有商品------------------");
            return;
        }
        DTLog(@"内购商品列表------%@",products);
    } failure:^(NSError *error) {
        DTLog(@"--------------请求商品失败--------------%@----",error);
    }];
}

-(void)SQ_buttonClick{
    //调用内购
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    WS(weakSelf);
     [[RMStore defaultStore] addPayment:self.seletedModel.appleId success:^(SKPaymentTransaction *transaction) {
            [weakSelf checkIAPResultWithtransactionReceiptblock];
        } failure:^(SKPaymentTransaction *transaction, NSError *error) {
            [YJProgressHUD showMsgWithoutView: SQNSLocalString(@"交易失败")];
    }];
    
}
- (void)checkIAPResultWithtransactionReceiptblock
{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
        if (receiptURL) {
            NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
            DTLog(@"%@",receiptData);
            NSString *encodeStr = [receiptData base64EncodedStringWithOptions: NSDataBase64EncodingEndLineWithLineFeed];
             NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
            [dic setObject:encodeStr forKey:@"certificate"];
             [YJProgressHUD SQ_showMsgWithoutView:@""];
            [HttpTool post:Url10 paramDic:dic successBlock:^(BaseModel * _Nullable httpModel) {
                
                for (SKPaymentTransaction *aTransaction in [[SKPaymentQueue defaultQueue] transactions]) {
                    [[SKPaymentQueue defaultQueue]finishTransaction:aTransaction];
                }
                [self SQ_goumaichenggong];
            } andFailBloc:^(BaseModel * _Nullable httpModel, NSError * _Nullable error) {
                [YJProgressHUD showMsgWithoutView:httpModel.message];
            }];
        }else{
            [YJProgressHUD hide];
           
        }
}
-(void)SQ_goumaichenggong{
    JieGuoView * vc = [[JieGuoView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    vc.oneLabel.text = SQNSLocalString(@"充值成功");
    vc.towLabel.text = SQNSLocalString(@"您已成功充值钻石，请进行使用");
    LSTPopView * pop = [LSTPopView initWithCustomView:vc
                                           parentView:nil
                                             popStyle:LSTPopStyleFade dismissStyle:LSTDismissStyleFade];
    pop.hemStyle = LSTHemStyleCenter;
    pop.isStack = YES;
    [pop pop];
    LSTPopViewWK(pop)
    WS(weakSelf);
    [vc setJGBlock:^{
        [wk_pop dismiss];
        if (weakSelf.CZBlock) {
            weakSelf.CZBlock(YES);
        } 
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
     return self.jsonArray.count;
}
 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChongzhiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChongzhiTableViewCell"];
    if (!cell) {
        cell = [[ChongzhiTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"ChongzhiTableViewCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = [self.jsonArray objectAtIndex:indexPath.item];
    return cell;
}
 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  96;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.seletedModel = [self.jsonArray objectAtIndex:indexPath.item];
   
}



-(UITableView*)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 295, 0) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0.01; // 这个属性，设置为0 时，headerView会随着滑动，给个最小值，就不会滑动了。
         }
        _tableView.allowsMultipleSelection = NO;
        if (@available(iOS 13.0, *)) {
            _tableView.automaticallyAdjustsScrollIndicatorInsets = NO;
        }
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedRowHeight = 0;
        }
    }
    return _tableView;
}
-(NSMutableArray*)jsonArray
{
    if (!_jsonArray) {
        _jsonArray = [[NSMutableArray alloc]init];
    }
    return _jsonArray;
}
@end


@implementation ChongzhiTableViewCell

- (void)SQ_setSelected:(BOOL)selected animated:(BOOL)animated{
    if (selected) {
        self.bgImage.hidden = NO;
    } else {
        self.bgImage.hidden = YES;
    }
}

- (void)SQ_Style:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    UIView * bgView = [[UIView alloc]init];
    bgView.backgroundColor = SQHexColor(@"#FFFFFF", 0.1);
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    [self.contentView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(80);
            make.top.equalTo(self.contentView);
            make.left.equalTo(self.contentView).offset(16);
    }];
    [self.contentView addSubview:self.bgImage];
    [self.bgImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(80);
            make.top.equalTo(self.contentView);
            make.left.equalTo(self.contentView).offset(16);
    }];
    
    UIImageView * zsimage = [[UIImageView alloc]init];
    zsimage.image = SQGetImage(@"钻石");
    zsimage.contentMode = UIViewContentModeScaleAspectFit;
    [bgView addSubview:zsimage];
    [zsimage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(32, 28));
        make.centerX.equalTo(bgView);
        make.top.equalTo(bgView).offset(12);
    }];
    [bgView addSubview:self.ZSLabel];
    [self.ZSLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(bgView).offset(54);
            make.centerX.equalTo(bgView);
    }];
    [self.contentView addSubview:self.moneyLabel];
    [self.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(bgView).offset(20);
            make.left.equalTo(bgView.mas_right).offset(16);
    }];
    [self.contentView addSubview:self.messageLabel];
    [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(bgView).offset(44);
            make.left.equalTo(bgView.mas_right).offset(16);
        make.height.mas_equalTo(16);
    }];
    [self.contentView addSubview:self.remarkLabel];
    [self.remarkLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.messageLabel.mas_bottom);
        make.left.equalTo(bgView.mas_right).offset(36);
    }];
    
  
}

- (void)setModel:(ZSModel *)model{
    _model = model;
    self.ZSLabel.text = [NSString stringWithFormat:@"%@%@",model.num,SQNSLocalString(@"钻石")];
    self.moneyLabel.text = [NSString stringWithFormat:@"%@%@",model.prefix,model.price];
    if ([model.give isNotEmpty]) {
        self.messageLabel.text = [NSString stringWithFormat:@"%@",model.give];
    }
    if ([model.remark isNotEmpty]) {
        self.remarkLabel.text = [NSString stringWithFormat:@"%@",model.remark];
    }
}



- (UIImageView *)bgImage{
    if (!_bgImage) {
        _bgImage = [[UIImageView alloc]init];
        _bgImage.image = SQGetImage(@"背景-2");
        _bgImage.contentMode = UIViewContentModeScaleAspectFit;
        _bgImage.hidden = YES;
    }
    return _bgImage;
}
- (UILabel *)ZSLabel{
    if (!_ZSLabel) {
        _ZSLabel = [[UILabel alloc]init];
        _ZSLabel.font = FONT_BOLD(12);
        _ZSLabel.textColor = UIColor.whiteColor;
        _ZSLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _ZSLabel;
}
- (UILabel *)moneyLabel{
    if (!_moneyLabel) {
        _moneyLabel = [[UILabel alloc]init];
        _moneyLabel.font = FONT_BOLD(12);
        _moneyLabel.textColor = UIColor.whiteColor;
        _moneyLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _moneyLabel;
}
- (UILabel *)messageLabel{
    if (!_messageLabel) {
        _messageLabel = [[UILabel alloc]init];
        _messageLabel.font = FONT_BOLD(12);
        _messageLabel.textColor = UIColor.whiteColor;
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        _messageLabel.numberOfLines = 0;
    }
    return _messageLabel;
}
- (UILabel *)remarkLabel{
    if (!_remarkLabel) {
        _remarkLabel = [[UILabel alloc]init];
        _remarkLabel.font = FONT_BOLD(12);
        _remarkLabel.textColor = UIColor.whiteColor;
        _remarkLabel.textAlignment = NSTextAlignmentCenter;
        _remarkLabel.numberOfLines = 0;
    }
    return _remarkLabel;
}
@end
